Component({
  properties: {
    // 从父组件接收的数据
    productInformation: {
      type: Object,
      value: {}
    },
    selectedServiceConfigs: {
      type: Object,
      value: {}
    },
    serviceConfigs: {
      type: Array,
      value: []
    },
    address: {
      type: Object,
      value: {}
    },
    selectedTimeInfo: {
      type: Object,
      value: {}
    },
    availableTimeList: {
      type: Array,
      value: []
    },
    fileList: {
      type: Array,
      value: []
    },
    printingMode: {
      type: String,
      value: 'single'
    },
    curPaperNum: {
      type: String,
      value: '1'
    },
    curCopyNum: {
      type: String,
      value: '1'
    },
    printNote: {
      type: String,
      value: ''
    }
  },

  data: {
    // 组件内部数据
    selectedServicePrice: '0',
    selectedServicePriceUnit: 'page',
    // 弹窗相关
    showCopyNumPopup: false,
    showPaperNumPopup: false,
    tempCopyNum: '',
    tempPaperNum: '',
    keyboardHeight: '0rpx'
  },

  lifetimes: {
    attached() {
      console.log('Print service component attached');
      console.log('Initial selectedServiceConfigs:', this.data.selectedServiceConfigs);
      console.log('Initial serviceConfigs:', this.data.serviceConfigs);
    }
  },

  observers: {
    'selectedServiceConfigs': function(newVal) {
      console.log('selectedServiceConfigs changed:', newVal);
      this.updateSelectedServicePrice();
    },
    'serviceConfigs': function(newVal) {
      console.log('serviceConfigs changed:', newVal);
    }
  },

  methods: {
    // 选择文件
    chooseFile() {
      wx.chooseMessageFile({
        count: 1,
        type: 'all',
        success: (res) => {
          const file = res.tempFiles[0];
          const maxSize = 50 * 1024 * 1024; // 50MB

          if (file.size > maxSize) {
            wx.showToast({
              title: '文件不能超过50MB',
              icon: 'none',
            });
            return;
          }

          this.uploadFileToCloud(file);
        },
        fail: (err) => {
          console.error('选择文件失败:', err);
          wx.showToast({
            title: '选择文件失败',
            icon: 'none',
          });
        },
      });
    },

    // 上传到云存储
    uploadFileToCloud(file) {
      const cloudPath = `print-uploads/${Date.now()}-${file.name}`;

      wx.showLoading({
        title: '上传中...',
        mask: true,
      });

      wx.cloud.uploadFile({
        cloudPath,
        filePath: file.path,
        success: (res) => {
          let publicFileUrl = this.getPublicURL(res.fileID);
          const newFile = {
            fileID: publicFileUrl,
            fileName: file.name,
            fileType: file.name.split('.').pop().toLowerCase(),
            fileSize: file.size
          };

          this.triggerEvent('fileListChange', {
            fileList: [newFile]
          });
          
          wx.hideLoading();
          wx.showToast({
            title: '上传成功',
            icon: 'success',
          });
        },
        fail: (err) => {
          console.error('上传失败', err);
          wx.hideLoading();
          wx.showToast({
            title: '上传失败',
            icon: 'none',
          });
        },
      });
    },

    // 删除文件
    removeFile(e) {
      const index = e.currentTarget.dataset.index;
      const fileList = this.data.fileList;
      
      wx.cloud.deleteFile({
        fileList: [fileList[index].fileID],
        success: () => {
          fileList.splice(index, 1);
          this.triggerEvent('fileListChange', { fileList });
          wx.showToast({ title: '删除成功', icon: 'success' });
        },
        fail: () => {
          wx.showToast({ title: '删除失败', icon: 'none' });
        }
      });
    },

    // 份数输入处理
    onCopyNumInput(e) {
      let value = e.detail.value;
      // 限制范围在1-100
      if (value < 1) value = 1;
      if (value > 100) value = 100;
      
      this.setData({
        curCopyNum: value.toString()
      });
      
      this.triggerEvent('copyNumChange', { curCopyNum: value.toString() });
      // 触发价格重新计算
      this.triggerEvent('priceRecalculate');
    },

    // 张数输入处理
    onPaperNumInput(e) {
      let value = e.detail.value;
      // 限制范围在1-100
      if (value < 1) value = 1;
      if (value > 100) value = 100;
      
      this.setData({
        curPaperNum: value.toString()
      });
      
      this.triggerEvent('paperNumChange', { curPaperNum: value.toString() });
      // 触发价格重新计算
      this.triggerEvent('priceRecalculate');
    },

    // 备注输入
    onNoteInput(e) {
      this.triggerEvent('printNoteChange', { printNote: e.detail.value });
    },

    // 获取公共URL
    getPublicURL(fileID) {
      if (!fileID.startsWith('cloud://')) return fileID;
      const envPart = fileID.split('/')[2];
      const envId = envPart.split('.')[1];
      const filePath = fileID.split('/').slice(3).join('/');
      const encodedPath = encodeURI(filePath);
      return `https://${envId}.tcb.qcloud.la/${encodedPath}`;
    },

    // 阻止事件冒泡
    preventBubble() {
      return;
    },

    // 地址选择
    onAddressSelect() {
      this.triggerEvent('addressSelect');
    },

    // 时间选择
    onTimeSelect() {
      this.triggerEvent('timeSelect');
    },

    // 选择服务配置
    selectServiceConfig(e) {
      const { serviceIndex, optionIndex } = e.currentTarget.dataset;
      const { serviceConfigs } = this.data;
      
      console.log('selectServiceConfig triggered:', { serviceIndex, optionIndex });
      
      const serviceConfig = serviceConfigs[serviceIndex];
      const selectedOption = serviceConfig.options[optionIndex];
      const optionKey = `${serviceIndex}_${optionIndex}`;
      
      // 互斥选择：清空所有选择，只选择当前点击的选项
      const newSelectedServiceConfigs = {};
      newSelectedServiceConfigs[optionKey] = {
        serviceIndex,
        optionIndex,
        selectedService: selectedOption,
        quantity: 1
      };
      
      console.log('Updating selectedServiceConfigs:', newSelectedServiceConfigs);
      
      // 更新组件内部状态
      this.setData({
        selectedServiceConfigs: newSelectedServiceConfigs
      });
      
      // 更新选中服务的价格信息
      this.updateSelectedServicePrice();
      
      // 触发父组件事件
      this.triggerEvent('serviceConfigChange', {
        selectedServiceConfigs: newSelectedServiceConfigs
      });
      
      // 触发价格重新计算
      this.triggerEvent('priceRecalculate');
      
      // 添加调试信息
      console.log('Current selectedServiceConfigs after update:', this.data.selectedServiceConfigs);
    },

    // 更新选中服务的价格信息
    updateSelectedServicePrice() {
      const { selectedServiceConfigs } = this.data;
      const selectedKeys = Object.keys(selectedServiceConfigs);
      
      if (selectedKeys.length > 0) {
        const selectedKey = selectedKeys[0];
        const selectedService = selectedServiceConfigs[selectedKey].selectedService;
        
        this.setData({
          selectedServicePrice: selectedService.price,
          selectedServicePriceUnit: selectedService.priceUnit
        });
      } else {
        this.setData({
          selectedServicePrice: '0',
          selectedServicePriceUnit: 'page'
        });
      }
    },

    // 显示数量输入弹窗
    showQuantityPopup(e) {
      const type = e.currentTarget.dataset.type;
      if (type === 'copy') {
        this.setData({
          showCopyNumPopup: true,
          tempCopyNum: this.data.curCopyNum || ''
        });
      } else if (type === 'paper') {
        this.setData({
          showPaperNumPopup: true,
          tempPaperNum: this.data.curPaperNum || ''
        });
      }
    },

    // 份数输入变化
    onCopyNumInputChange(e) {
      this.setData({
        tempCopyNum: e.detail.value
      });
    },

    // 张数输入变化
    onPaperNumInputChange(e) {
      this.setData({
        tempPaperNum: e.detail.value
      });
    },

    // 确认份数
    confirmCopyNum() {
      const copyNum = this.data.tempCopyNum;
      if (!copyNum || copyNum < 1 || copyNum > 100) {
        wx.showToast({
          title: '请输入1-100的份数',
          icon: 'none'
        });
        return;
      }
      
      this.setData({
        showCopyNumPopup: false
      });
      
      this.triggerEvent('copyNumChange', {
        curCopyNum: copyNum
      });
      
      // 触发价格重新计算
      this.triggerEvent('priceRecalculate');
    },

    // 确认张数
    confirmPaperNum() {
      const paperNum = this.data.tempPaperNum;
      if (!paperNum || paperNum < 1 || paperNum > 100) {
        wx.showToast({
          title: '请输入1-100的张数',
          icon: 'none'
        });
        return;
      }
      
      this.setData({
        showPaperNumPopup: false
      });
      
      this.triggerEvent('paperNumChange', {
        curPaperNum: paperNum
      });
      
      // 触发价格重新计算
      this.triggerEvent('priceRecalculate');
    },

    // 键盘高度变化
    onKeyboardheightchange(e) {
      const height = e.detail.height || 0;
      this.setData({
        keyboardHeight: height + 'px'
      });
    },

    // 弹窗输入框获取焦点时全选
    onPopupInputFocus(e) {
      const that = this;
      setTimeout(() => {
        // 使用 createSelectorQuery 获取输入框并全选
        const query = that.createSelectorQuery();
        query.select('.popup-input').context().exec((res) => {
          if (res[0] && res[0].context) {
            res[0].context.setSelectionRange(0, -1);
          }
        });
      }, 50);
    }
  }
}); 